package mysql

import (
	"context"
	"data-transfer/domain"
	"fmt"
	"github.com/shopspring/decimal"
	"sync/atomic"
)

// InsertTest 仅为测试用
func (mdb *db) InsertTest(ctx context.Context, rows []*domain.TEST_TARGET) (int64, error) {
	affected, err := mdb.db.NewSession().Insert(rows)
	return affected, err
}

//DeleteBizData 初始化前删除业务数据
func (mdb *db) DeleteBizData(tableName string) (int64, error) {

	delSql := "DELETE FROM " + tableName + " WHERE ID > 0;"
	var err error
	result, err := mdb.db.Exec(delSql)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()

}

// InsertKeyIndicator 新增财务数据指标
func (mdb *db) InsertKeyIndicator(ctx context.Context, rows []*domain.KEY_INDICATOR) (int64, error) {
	checkKeyIndicatorDecimalNull(rows)

	var affected int64
	var err error
	execFun := func(index int) {
		r := rows[index]
		aff, e := mdb.db.NewSession().Insert(r)
		if e != nil {
			err = e
		}
		atomic.AddInt64(&affected, aff)
	}
	DoBatch(len(rows), 50, execFun)

	return affected, err
}

//InsertKeyIndicatorSq 新增财务数据主要指标单季度
func (mdb *db) InsertKeyIndicatorSq(ctx context.Context, rows []*domain.KEY_INDICATOR_SQ) (int64, error) {
	checkKeyIndicatorSqDecimalNull(rows)

	var affected int64
	var err error
	execFun := func(index int) {
		r := rows[index]
		aff, e := mdb.db.NewSession().Insert(r)
		if e != nil {
			err = e
		}
		atomic.AddInt64(&affected, aff)
	}
	DoBatch(len(rows), 50, execFun)

	return affected, err
}

// InsertBalanceSheet 新增财务数据-资产负债表
func (mdb *db) InsertBalanceSheet(ctx context.Context, rows []*domain.BALANCE_SHEET) (int64, error) {
	checkBalanceSheetDecimalNull(rows)

	var affected int64
	var err error
	execFun := func(index int) {
		r := rows[index]
		aff, e := mdb.db.NewSession().Insert(r)
		if e != nil {
			err = e
		}
		atomic.AddInt64(&affected, aff)
	}
	DoBatch(len(rows), 50, execFun)

	return affected, err
}

// InsertIncomeStatement 新增财务数据-企业利润表
func (mdb *db) InsertIncomeStatement(ctx context.Context, rows []*domain.INCOME_STATEMENT) (int64, error) {
	checkIncomeStatementDecimalNull(rows)

	var affected int64
	var err error
	execFun := func(index int) {
		r := rows[index]
		aff, e := mdb.db.NewSession().Insert(r)
		if e != nil {
			err = e
		}
		atomic.AddInt64(&affected, aff)
	}
	DoBatch(len(rows), 50, execFun)

	return affected, err
}

// InsertIncomeStatementSq 新增财务数据-企业利润表
func (mdb *db) InsertIncomeStatementSq(ctx context.Context, rows []*domain.INCOME_STATEMENT_SQ) (int64, error) {
	checkIncomeStatementSqDecimalNull(rows)

	var affected int64
	var err error
	execFun := func(index int) {
		r := rows[index]
		aff, e := mdb.db.NewSession().Insert(r)
		if e != nil {
			err = e
		}
		atomic.AddInt64(&affected, aff)
	}
	DoBatch(len(rows), 50, execFun)

	return affected, err
}

// InsertCashFlow 新增现金流
func (mdb *db) InsertCashFlow(ctx context.Context, rows []*domain.CASH_FLOW) (int64, error) {
	checkCashFlowDecimalNull(rows)

	var affected int64
	var err error
	execFun := func(index int) {
		r := rows[index]
		aff, e := mdb.db.NewSession().Insert(r)
		if e != nil {
			err = e
		}
		atomic.AddInt64(&affected, aff)
	}
	DoBatch(len(rows), 50, execFun)

	return affected, err
}

// InsertCashFlowSq 新增单季度现金流
func (mdb *db) InsertCashFlowSq(ctx context.Context, rows []*domain.CASH_FLOW_SQ) (int64, error) {
	checkCashFlowSqDecimalNull(rows)

	var affected int64
	var err error
	execFun := func(index int) {
		r := rows[index]
		aff, e := mdb.db.NewSession().Insert(r)
		if e != nil {
			err = e
		}
		atomic.AddInt64(&affected, aff)
	}
	DoBatch(len(rows), 50, execFun)

	return affected, err
}

// DeleteCashFlow 删除现金流
func (mdb *db) DeleteCashFlow(deleteSql string, deleteMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(deleteSql, deleteMap["COMPCODE"], deleteMap["REPORTYEAR"], deleteMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

// UpdateCashFLow 更新现金流
func (mdb *db) UpdateCashFLow(updateSql string, updateMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(updateSql, updateMap["BIZCASHINFL"], updateMap["BIZCASHOUTF"],
		updateMap["MANANETR"], updateMap["INVCASHINFL"], updateMap["INVCASHOUTF"], updateMap["INVNETCASHFLOW"], updateMap["FINCASHINFL"],
		updateMap["FINCASHOUTF"], updateMap["FINNETCFLOW"], updateMap["CASHNETR"], updateMap["COMPCODE"], updateMap["REPORTYEAR"], updateMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

//DeleteCashFlowSq 删除现金流-单季度
func (mdb *db) DeleteCashFlowSq(deleteSql string, deleteMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(deleteSql, deleteMap["COMPCODE"], deleteMap["REPORTYEAR"], deleteMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

// UpdateCashFLowSq 更新现金流-单季度
func (mdb *db) UpdateCashFLowSq(updateSql string, updateMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(updateSql, updateMap["BIZCASHINFLOPI"], updateMap["BIZCASHOUTFOPO"], updateMap["MANANETR"], updateMap["INVCASHINFLINVI"], updateMap["INVCASHOUTFINVO"], updateMap["INVNETCASHFLOW"],
		updateMap["FINCASHINFLFINI"], updateMap["FINCASHOUTFFINO"], updateMap["FINNETCFLOW"], updateMap["CASHNETR"], updateMap["COMPCODE"], updateMap["REPORTYEAR"], updateMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

//InsertCashFlowSqSingle 新增现金流数据-单季度，用于gocanal监控
func (mdb *db) InsertCashFlowSqSingle(insertSql string, insertedMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(insertSql, insertedMap["REPORTYEAR"], insertedMap["REPORTDATETYPE"], insertedMap["BIZCASHINFLOPI"], insertedMap["BIZCASHOUTFOPO"], insertedMap["MANANETR"],
		insertedMap["INVCASHINFLINVI"], insertedMap["INVCASHOUTFINVO"], insertedMap["INVNETCASHFLOW"], insertedMap["FINCASHINFLFINI"], insertedMap["FINCASHOUTFFINO"], insertedMap["FINNETCFLOW"],
		insertedMap["CASHNETR"], insertedMap["SYMBOL"], insertedMap["COMPCODE"], insertedMap["EXCHANGE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

// InsertCashFlowSingle 新增现金流数据，用于gocanal监控
func (mdb *db) InsertCashFlowSingle(insertSql string, insertedMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(insertSql, insertedMap["REPORTYEAR"], insertedMap["REPORTDATETYPE"], insertedMap["BIZCASHINFL"], insertedMap["BIZCASHOUTF"],
		insertedMap["MANANETR"], insertedMap["INVCASHINFL"], insertedMap["INVCASHOUTF"], insertedMap["INVNETCASHFLOW"], insertedMap["FINCASHINFL"],
		insertedMap["FINCASHOUTF"], insertedMap["FINNETCFLOW"], insertedMap["CASHNETR"], insertedMap["SYMBOL"], insertedMap["COMPCODE"], insertedMap["EXCHANGE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

// InsertIncomeStatementSingle 新增一般企业利润表数据，用于gocanal监控
func (mdb *db) InsertIncomeStatementSingle(insertSql string, insertedMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(insertSql, insertedMap["SYMBOL"], insertedMap["REPORTYEAR"], insertedMap["REPORTDATETYPE"], insertedMap["BIZTOTINCO"], insertedMap["BIZTOTCOST"],
		insertedMap["MANAEXPE"], insertedMap["SALESEXPE"], insertedMap["FINEXPE"], insertedMap["PERPROFIT"], insertedMap["INVEINCO"], insertedMap["NONOREVE"], insertedMap["NONOEXPE"], insertedMap["TOTPROFIT"], insertedMap["NETPROFIT"], insertedMap["COMPCODE"], insertedMap["EXCHANGE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

// DeleteIncomeStatement 删除一般企业利润表数据
func (mdb *db) DeleteIncomeStatement(deleteSql string, deleteMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(deleteSql, deleteMap["COMPCODE"], deleteMap["REPORTYEAR"], deleteMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

//DeleteKeyIndicatorSq 删除财务数据-主要指标-单季度
func (mdb *db) DeleteKeyIndicatorSq(deleteSql string, deleteMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(deleteSql, deleteMap["COMPCODE"], deleteMap["REPORTYEAR"], deleteMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

// UpdateIncomeStatement 更新一般企业利润表数据
func (mdb *db) UpdateIncomeStatement(updateSql string, updateMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(updateSql, updateMap["BIZTOTINCO"], updateMap["BIZTOTCOST"], updateMap["MANAEXPE"], updateMap["SALESEXPE"], updateMap["FINEXPE"], updateMap["PERPROFIT"], updateMap["INVEINCO"], updateMap["NONOREVE"], updateMap["NONOEXPE"],
		updateMap["TOTPROFIT"], updateMap["NETPROFIT"], updateMap["COMPCODE"], updateMap["REPORTYEAR"], updateMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

// UpdateBalanceSheet 更新资产负债信息
func (mdb *db) UpdateBalanceSheet(updateSql string, updateMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(updateSql, updateMap["TOTCURRASSET"], updateMap["CURFDS"], updateMap["TRADFINASSET"], updateMap["INVE"], updateMap["ACCORECE"], updateMap["OTHERRECETOT"],
		updateMap["TOTALNONCASSETS"], updateMap["FIXEDASSENET"], updateMap["AVAISELLASSE"], updateMap["INTAASSET"], updateMap["GOODWILL"], updateMap["TOTASSET"], updateMap["TOTALCURRLIAB"],
		updateMap["ADVAPAYM"], updateMap["ACCOPAYA"], updateMap["TOTALNONCLIAB"], updateMap["TOTLIAB"], updateMap["PARESHARRIGH"], updateMap["CAPISURP"], updateMap["SHORTTERMBORR"],
		updateMap["COMPCODE"], updateMap["REPORTYEAR"], updateMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

// InsertBalanceSheetSingle  新增一般资产负债数据，用于gocanal监控
func (mdb *db) InsertBalanceSheetSingle(insertSql string, insertedMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(insertSql, insertedMap["REPORTYEAR"], insertedMap["REPORTDATETYPE"], insertedMap["TOTCURRASSET"], insertedMap["CURFDS"], insertedMap["TRADFINASSET"],
		insertedMap["INVE"], insertedMap["ACCORECE"], insertedMap["OTHERRECETOT"], insertedMap["TOTALNONCASSETS"], insertedMap["FIXEDASSENET"], insertedMap["AVAISELLASSE"],
		insertedMap["INTAASSET"], insertedMap["GOODWILL"], insertedMap["TOTASSET"], insertedMap["TOTALCURRLIAB"], insertedMap["ADVAPAYM"], insertedMap["ACCOPAYA"], insertedMap["TOTALNONCLIAB"],
		insertedMap["TOTLIAB"], insertedMap["PARESHARRIGH"], insertedMap["CAPISURP"], insertedMap["SHORTTERMBORR"], insertedMap["SYMBOL"], insertedMap["COMPCODE"], insertedMap["EXCHANGE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

//UpdateKeyIndicatorSq 更新财务数据主要指标数据-单季度
func (mdb *db) UpdateKeyIndicatorSq(updateSql string, updateMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(updateSql, updateMap["EPSBASIC"], updateMap["CRPS"], updateMap["NAPS"], updateMap["UPPS"], updateMap["OPNCFPS"], updateMap["SGPMARGIN"], updateMap["OPPRORT"],
		updateMap["PROFITRATIO"], updateMap["ROEWEIGHTED"], updateMap["ROEDILUTED"], updateMap["CURRENTRT"], updateMap["QUICKRT"], updateMap["COMPCODE"], updateMap["REPORTYEAR"], updateMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

// InsertKeyIndicatorSqSingle 新增财务数据主要指标数据-单季度
func (mdb *db) InsertKeyIndicatorSqSingle(insertSql string, insertedMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(insertSql, insertedMap["REPORTYEAR"], insertedMap["REPORTDATETYPE"], insertedMap["EPSBASIC"], insertedMap["CRPS"], insertedMap["NAPS"], insertedMap["UPPS"], insertedMap["OPNCFPS"], insertedMap["SGPMARGIN"], insertedMap["OPPRORT"], insertedMap["PROFITRATIO"], insertedMap["ROEWEIGHTED"], insertedMap["ROEDILUTED"],
		insertedMap["CURRENTRT"], insertedMap["QUICKRT"], insertedMap["SYMBOL"], insertedMap["COMPCODE"], insertedMap["EXCHANGE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

//UpdateIncomeStatementSq 更新财务数据-利润表-单季度
func (mdb *db) UpdateIncomeStatementSq(updateSql string, updateMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(updateSql, updateMap["BIZINCO"], updateMap["BIZCOST"], updateMap["MGTEXPE"], updateMap["OPEXPE"], updateMap["FINLEXPE"], updateMap["OPPROFIT"],
		updateMap["INVEINCO"], updateMap["NONBIZINCO"], updateMap["NONBIZCOST"], updateMap["TOTPROFIT"], updateMap["NETPROFITCONMS"], updateMap["COMPCODE"], updateMap["REPORTYEAR"], updateMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

//InsertIncomeStatementSqSingle 新增财务数据-利润表-单季度
func (mdb *db) InsertIncomeStatementSqSingle(insertSql string, insertedMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(insertSql, insertedMap["SYMBOL"], insertedMap["REPORTYEAR"], insertedMap["REPORTDATETYPE"], insertedMap["BIZINCO"], insertedMap["BIZCOST"], insertedMap["MGTEXPE"],
		insertedMap["OPEXPE"], insertedMap["FINLEXPE"], insertedMap["OPPROFIT"], insertedMap["INVEINCO"], insertedMap["NONBIZINCO"], insertedMap["NONBIZCOST"], insertedMap["TOTPROFIT"], insertedMap["NETPROFITCONMS"], insertedMap["COMPCODE"], insertedMap["EXCHANGE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

//DeleteIncomeStatementSq  删除财务数据-利润表-单季度
func (mdb *db) DeleteIncomeStatementSq(deleteSql string, deleteMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(deleteSql, deleteMap["COMPCODE"], deleteMap["REPORTYEAR"], deleteMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

//UpdateIncomeStatement4Bank 针对银行利润表更新财务利润信息
func (mdb *db) UpdateIncomeStatement4Bank(updateMap map[string]string) (int64, error) {
	defaultVal := "0.000000" //数值型默认值
	bizTotInco := ""         //营业收入
	bizTotCost := ""         //营业成本
	//manaExpe := "" //管理费用
	//salesExpe := "" //营业费用
	//finExpe := "" //财务费用
	perProfit := "" //营业利润
	inveInco := ""  //投资利益
	nonoReve := ""  //营业外收入净额
	nonoExpe := ""  //营业外支出净额
	totProfit := "" //利润总额
	netProfit := "" //净利润
	//BIZADMINEXPEN	业务及管理费用
	bizAdminExpen := "" //银行业务及管理费用

	//通用参数
	reportYear := ""
	reportDateType := ""
	compCode, _ := updateMap["COMPCODE"]

	updateSql := "UPDATE INCOME_STATEMENT SET COMPCODE = " + fmt.Sprintf("%v", compCode) //compCode肯定是有，确保update语句正确

	if bizincoI, ok := updateMap["BIZINCO"]; ok { //营业收入
		if bizincoI == "" {
			bizTotInco = defaultVal
		} else {
			bizTotInco = bizincoI
		}
	}

	if bizcostI, ok := updateMap["BIZCOST"]; ok { //营业成本
		if bizcostI == "" {
			bizTotCost = defaultVal
		} else {
			bizTotCost = bizcostI
		}
	}

	//银行三费合一： SALESEXPE	销售费用|MANAEXPE	管理费用|FINEXPE	财务费用
	if bizAdminExpenI, ok := updateMap["BIZADMINEXPEN"]; ok { //银行业务及管理费用
		if bizAdminExpenI == "" {
			bizAdminExpen = defaultVal
		} else {
			bizAdminExpen = bizAdminExpenI
		}
	}

	if perProfitI, ok := updateMap["PERPROFIT"]; ok { //营业利润
		if perProfitI == "" {
			perProfit = defaultVal
		} else {
			perProfit = perProfitI
		}
	}

	if inveIncoI, ok := updateMap["INVEINCO"]; ok { //投资收益
		if inveIncoI == "" {
			inveInco = defaultVal
		} else {
			inveInco = inveIncoI
		}
	}

	if nonoReveI, ok := updateMap["NONOREVE"]; ok { //营业外收入
		if nonoReveI == "" {
			nonoReve = defaultVal
		} else {
			nonoReve = nonoReveI
		}
	}

	if nonoExpeI, ok := updateMap["NONOEXPE"]; ok { //营业外支出
		if nonoExpeI == "" {
			nonoExpe = defaultVal
		} else {
			nonoExpe = nonoExpeI
		}
	}

	//营业外收支净额
	//设置营业外收支净额
	nonoreveDec, _ := decimal.NewFromString(nonoReve)
	nonoexpeDec, _ := decimal.NewFromString(nonoExpe)
	nnoiDec := nonoreveDec.Sub(nonoexpeDec)
	nonoReve = nnoiDec.String() //营业外收支净额

	if totProfitI, ok := updateMap["TOTPROFIT"]; ok { //利润总额
		if totProfitI == "" {
			totProfit = defaultVal
		} else {
			totProfit = totProfitI
		}
	}

	if netProfitI, ok := updateMap["NETPROFIT"]; ok { //净利润
		if netProfitI == "" {
			netProfit = defaultVal
		} else {
			netProfit = netProfitI
		}
	}

	if len(bizTotInco) > 0 { //营业收入
		updateSql += ",BIZTOTINCO=" + bizTotInco
	}

	if len(bizTotCost) > 0 { //营业成本
		updateSql += ",BIZTOTCOST=" + bizTotCost
	}

	if len(bizAdminExpen) > 0 { //管理费用、销售费用、财务费用 三费合一
		updateSql += ",SALESEXPE=" + bizAdminExpen
		updateSql += ",MANAEXPE=" + bizAdminExpen
		updateSql += ",FINEXPE=" + bizAdminExpen
	}

	//营业外收支净额
	if len(nonoReve) > 0 {
		updateSql += ",NONOREVE=" + nonoReve
	}

	//营业利润
	if len(perProfit) > 0 {
		updateSql += ",PERPROFIT=" + perProfit
	}

	//投资收益
	if len(inveInco) > 0 {
		updateSql += ",INVEINCO=" + inveInco
	}

	//利润总额
	if len(totProfit) > 0 {
		updateSql += ",TOTPROFIT=" + totProfit
	}

	//净利润
	if len(netProfit) > 0 {
		updateSql += ",NETPROFIT=" + netProfit
	}

	// 拼接where 通用条件
	updateSql += " WHERE COMPCODE = " + fmt.Sprintf("%v", compCode) + " AND ID > 0 " // 确保SQL语句能够通过

	if reportYearI, ok := updateMap["REPORTYEAR"]; ok {
		reportYear = fmt.Sprintf("%v", reportYearI)
	}

	if reportDateTypeI, ok := updateMap["REPORTDATETYPE"]; ok {
		reportDateType = fmt.Sprintf("%v", reportDateTypeI)
	}

	if len(reportYear) > 0 {
		updateSql += " AND REPORTYEAR=" + reportYear
	}
	if len(reportDateType) > 0 {
		updateSql += " AND REPORTDATETYPE=" + reportDateType
	}

	symbol := ""
	if symbolI, ok := updateMap["SYMBOL"]; ok {
		symbol = fmt.Sprintf("%v", symbolI)
	}

	if len(symbol) > 0 {
		updateSql += " AND SYMBOL=" + symbol
	}

	var err error
	result, err := mdb.db.Exec(updateSql)
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err

}

//UpdateKeyIndicator 更新财务数据主要指标数据
func (mdb *db) UpdateKeyIndicator(updateMap map[string]string) (int64, error) {
	defaultVal := "0.000000" //数值型默认值
	//主要财务指标(产品表）
	epsBasic := ""
	naps := ""
	opncfps := ""
	roeweighted := ""
	roediluted := ""

	//衍生财务指标(产品表)_V3
	crps := ""
	upps := ""
	snpmarginconms := ""
	opprort := ""
	currentrt := ""
	quickrt := ""

	//衍生财务指标副表(产品表)_V3
	profitratio := ""
	//通用参数
	reportYear := ""
	reportDateType := ""
	compCode, _ := updateMap["COMPCODE"]

	updateSql := "UPDATE KEY_INDICATOR SET COMPCODE = " + fmt.Sprintf("%v", compCode) //compCode肯定是有，确保update语句正确

	//-------------------------------------主要财务指标(产品表）-------------------------------
	//以下map中的Key,确保是要存在的，如果不存在，则赋值为空
	if epsBasicI, ok := updateMap["EPSBASIC"]; ok {
		if epsBasicI == "" {
			epsBasic = defaultVal
		} else {
			epsBasic = epsBasicI
		}
	}

	if napsI, ok := updateMap["NAPS"]; ok {
		if napsI == "" {
			naps = defaultVal
		} else {
			naps = napsI
		}
	}

	if opncfpsI, ok := updateMap["OPNCFPS"]; ok {
		if opncfpsI == "" {
			opncfps = defaultVal
		} else {
			opncfps = opncfpsI
		}
	}

	if roeweightedI, ok := updateMap["ROEWEIGHTED"]; ok {
		if roeweightedI == "" {
			roeweighted = defaultVal
		} else {
			roeweighted = roeweightedI
		}
	}

	if roedilutedI, ok := updateMap["ROEDILUTED"]; ok {
		if roedilutedI == "" {
			roeweighted = defaultVal
		} else {
			roeweighted = roedilutedI
		}
	}

	if len(epsBasic) > 0 {
		updateSql += ",EPSBASIC=" + epsBasic
	}

	if len(naps) > 0 {
		updateSql += ",NAPS=" + naps
	}

	if len(opncfps) > 0 {
		updateSql += ",OPNCFPS=" + opncfps
	}

	if len(roeweighted) > 0 {
		updateSql += ",ROEWEIGHTED=" + roeweighted
	}

	if len(roediluted) > 0 {
		updateSql += ",ROEDILUTED=" + roediluted
	}

	//-------------------------------------------衍生财务指标(产品表)_V3--------------------------------
	if crpsI, ok := updateMap["CRPS"]; ok {
		if crpsI == "" {
			crps = defaultVal
		} else {
			crps = crpsI
		}
	}

	if uppsI, ok := updateMap["UPPS"]; ok {
		if uppsI == "" {
			upps = defaultVal
		} else {
			upps = uppsI
		}
	}

	if snpmarginconmsI, ok := updateMap["SNPMARGINCONMS"]; ok {
		if snpmarginconmsI == "" {
			snpmarginconms = defaultVal
		} else {
			snpmarginconms = snpmarginconmsI
		}
	}

	if opprortI, ok := updateMap["OPPRORT"]; ok {
		if opprortI == "" {
			opprort = defaultVal
		} else {
			opprort = opprortI
		}
	}

	if currentrtI, ok := updateMap["CURRENTRT"]; ok {
		if currentrtI == "" {
			currentrt = defaultVal
		} else {
			currentrt = currentrtI
		}
	}
	if quickrtI, ok := updateMap["QUICKRT"]; ok {
		if quickrtI == "" {
			quickrt = defaultVal
		} else {
			quickrt = quickrtI
		}
	}

	if len(crps) > 0 {
		updateSql += ", CRPS=" + crps
	}

	if len(upps) > 0 {
		updateSql += ", UPPS=" + upps
	}
	if len(snpmarginconms) > 0 {
		updateSql += ", SNPMARGINCONMS=" + snpmarginconms
	}

	if len(opprort) > 0 {
		updateSql += ", OPPRORT=" + opprort
	}
	if len(currentrt) > 0 {
		updateSql += ", CURRENTRT=" + currentrt
	}

	if len(quickrt) > 0 {
		updateSql += ", QUICKRT=" + quickrt
	}

	// --------------------------------衍生财务指标副表(产品表)_V3-------------------------------
	if profitratioI, ok := updateMap["PROFITRATIO"]; ok {
		if profitratioI == "" {
			profitratio = defaultVal
		} else {
			profitratio = profitratioI
		}
	}
	if len(profitratio) > 0 {
		updateSql += ", PROFITRATIO=" + profitratio
	}

	// 拼接where 通用条件
	updateSql += " WHERE COMPCODE = " + fmt.Sprintf("%v", compCode) + " AND ID > 0 " // 确保SQL语句能够通过

	if reportYearI, ok := updateMap["REPORTYEAR"]; ok {
		reportYear = fmt.Sprintf("%v", reportYearI)
	}

	if reportDateTypeI, ok := updateMap["REPORTDATETYPE"]; ok {
		reportDateType = fmt.Sprintf("%v", reportDateTypeI)
	}

	if len(reportYear) > 0 {
		updateSql += " AND REPORTYEAR=" + reportYear
	}
	if len(reportDateType) > 0 {
		updateSql += " AND REPORTDATETYPE=" + reportDateType
	}

	symbol := ""

	if symbolI, ok := updateMap["SYMBOL"]; ok {
		symbol = fmt.Sprintf("%v", symbolI)
	}

	if len(symbol) > 0 {
		updateSql += " AND SYMBOL=" + symbol
	}

	var err error
	result, err := mdb.db.Exec(updateSql)
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

// DeleteBalanceSheet 删除资产负债数据
func (mdb *db) DeleteBalanceSheet(deleteSql string, deleteMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(deleteSql, deleteMap["COMPCODE"], deleteMap["REPORTYEAR"], deleteMap["REPORTDATETYPE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

//HasKeyIndicator 根据参数取得财务主要指标
func (mdb *db) HasKeyIndicator(compCode string, symbol string, reportYear string, reportDateType string) (bool, error) {
	keyIndicator := new(domain.KEY_INDICATOR)
	has, err := mdb.db.NewSession().Where("SYMBOL=? and COMPCODE = ? and REPORTYEAR = ?  and REPORTDATETYPE = ? ", symbol, compCode, reportYear, reportDateType).Desc("REPORTYEAR").Get(keyIndicator)
	return has, err
}

//HasIncomeStatement 根据参数判断是否含有财务企业利润数据
func (mdb *db) HasIncomeStatement(compCode string, symbol string, reportYear string, reportDateType string) (bool, error) {
	keyIndicator := new(domain.INCOME_STATEMENT)
	has, err := mdb.db.NewSession().Where("SYMBOL=? and COMPCODE = ? and REPORTYEAR = ?  and REPORTDATETYPE = ? ", symbol, compCode, reportYear, reportDateType).Desc("REPORTYEAR").Get(keyIndicator)
	return has, err
}

// InsertKeyIndicatorSingle 新增财务数据主要指标数据
func (mdb *db) InsertKeyIndicatorSingle(insertSql string, insertedMap map[string]interface{}) (int64, error) {
	var err error
	result, err := mdb.db.Exec(insertSql, insertedMap["REPORTYEAR"], insertedMap["REPORTDATETYPE"], insertedMap["EPSBASIC"], insertedMap["CRPS"], insertedMap["NAPS"], insertedMap["UPPS"],
		insertedMap["OPNCFPS"], insertedMap["SNPMARGINCONMS"], insertedMap["OPPRORT"], insertedMap["PROFITRATIO"], insertedMap["ROEWEIGHTED"], insertedMap["ROEDILUTED"],
		insertedMap["CURRENTRT"], insertedMap["QUICKRT"], insertedMap["SYMBOL"], insertedMap["COMPCODE"], insertedMap["EXCHANGE"])
	if err != nil {
		return 0, err
	}
	affected, err := result.RowsAffected()
	return affected, err
}

// checkCashFlowDecimalNull 简单处理decimal 类型为空的情况
// TODO 后续更改为 https://github.com/shopspring/decimal
func checkCashFlowDecimalNull(rows []*domain.CASH_FLOW) {
	defVal := "0.000000"
	for _, v := range rows {
		if v.Bizcashinfl == "" {
			v.Bizcashinfl = defVal
		}
		if v.Bizcashoutf == "" {
			v.Bizcashoutf = defVal
		}
		if v.Mananetr == "" {
			v.Mananetr = defVal
		}
		if v.Invcashinfl == "" {
			v.Invcashinfl = defVal
		}
		if v.Invcashoutf == "" {
			v.Invcashoutf = defVal
		}
		if v.Invnetcashflow == "" {
			v.Invnetcashflow = defVal
		}
		if v.Fincashinfl == "" {
			v.Fincashinfl = defVal
		}
		if v.Fincashoutf == "" {
			v.Fincashoutf = defVal
		}
		if v.Finnetcflow == "" {
			v.Finnetcflow = defVal
		}
		if v.Cashnetr == "" {
			v.Cashnetr = defVal
		}
	}
}

// checkCashFlowSqDecimalNull 简单处理decimal 类型为空的情况
// TODO 后续更改为 https://github.com/shopspring/decimal
func checkCashFlowSqDecimalNull(rows []*domain.CASH_FLOW_SQ) {
	defVal := "0.000000"
	for _, v := range rows {
		if v.Bizcashinfl == "" {
			v.Bizcashinfl = defVal
		}
		if v.Bizcashoutf == "" {
			v.Bizcashoutf = defVal
		}
		if v.Mananetr == "" {
			v.Mananetr = defVal
		}
		if v.Invcashinfl == "" {
			v.Invcashinfl = defVal
		}
		if v.Invcashoutf == "" {
			v.Invcashoutf = defVal
		}
		if v.Invnetcashflow == "" {
			v.Invnetcashflow = defVal
		}
		if v.Fincashinfl == "" {
			v.Fincashinfl = defVal
		}
		if v.Fincashoutf == "" {
			v.Fincashoutf = defVal
		}
		if v.Finnetcflow == "" {
			v.Finnetcflow = defVal
		}
		if v.Cashnetr == "" {
			v.Cashnetr = defVal
		}
	}
}

// checkIncomeStatementSqDecimalNull 简单处理decimal 类型为空的情况
// TODO 后续更改为 https://github.com/shopspring/decimal
func checkIncomeStatementSqDecimalNull(rows []*domain.INCOME_STATEMENT_SQ) {
	defVal := "0.000000"
	for _, v := range rows {
		if v.Biztotinco == "" {
			v.Biztotinco = defVal
		}
		if v.Biztotcost == "" {
			v.Biztotcost = defVal
		}
		if v.Manaexpe == "" {
			v.Manaexpe = defVal
		}
		if v.Salesexpe == "" {
			v.Salesexpe = defVal
		}
		if v.Finexpe == "" {
			v.Finexpe = defVal
		}
		if v.Perprofit == "" {
			v.Perprofit = defVal
		}
		if v.Inveinco == "" {
			v.Inveinco = defVal
		}
		if v.Nonoreve == "" {
			v.Nonoreve = defVal
		}
		if v.Nonoexpe == "" {
			v.Nonoexpe = defVal
		}
		if v.Totprofit == "" {
			v.Totprofit = defVal
		}
		if v.Netprofit == "" {
			v.Netprofit = defVal
		}
	}
}

// checkIncomeStatementDecimalNull 简单处理decimal 类型为空的情况
// TODO 后续更改为 https://github.com/shopspring/decimal
func checkIncomeStatementDecimalNull(rows []*domain.INCOME_STATEMENT) {
	defVal := "0.000000"
	for _, v := range rows {
		if v.Biztotinco == "" {
			v.Biztotinco = defVal
		}
		if v.Biztotcost == "" {
			v.Biztotcost = defVal
		}
		if v.Manaexpe == "" {
			v.Manaexpe = defVal
		}
		if v.Salesexpe == "" {
			v.Salesexpe = defVal
		}
		if v.Finexpe == "" {
			v.Finexpe = defVal
		}
		if v.Perprofit == "" {
			v.Perprofit = defVal
		}
		if v.Inveinco == "" {
			v.Inveinco = defVal
		}
		if v.Nonoreve == "" {
			v.Nonoreve = defVal
		}
		if v.Nonoexpe == "" {
			v.Nonoexpe = defVal
		}
		if v.Totprofit == "" {
			v.Totprofit = defVal
		}
		if v.Netprofit == "" {
			v.Netprofit = defVal
		}
	}
}

// checkBalanceSheetDecimalNull 简单处理decimal 类型为空的情况
// TODO 后续更改为 https://github.com/shopspring/decimal
func checkBalanceSheetDecimalNull(rows []*domain.BALANCE_SHEET) {
	defVal := "0.000000"
	for _, v := range rows {
		if v.Totcurrasset == "" {
			v.Totcurrasset = defVal
		}
		if v.Curfds == "" {
			v.Curfds = defVal
		}
		if v.Tradfinasset == "" {
			v.Tradfinasset = defVal
		}
		if v.Inve == "" {
			v.Inve = defVal
		}
		if v.Accorece == "" {
			v.Accorece = defVal
		}
		if v.Otherrecetot == "" {
			v.Otherrecetot = defVal
		}
		if v.Totalnoncassets == "" {
			v.Totalnoncassets = defVal
		}
		if v.Fixedassenet == "" {
			v.Fixedassenet = defVal
		}
		if v.Avaisellasse == "" {
			v.Avaisellasse = defVal
		}
		if v.Intaasset == "" {
			v.Intaasset = defVal
		}
		if v.Goodwill == "" {
			v.Goodwill = defVal
		}
		if v.Totasset == "" {
			v.Totasset = defVal
		}
		if v.Totalcurrliab == "" {
			v.Totalcurrliab = defVal
		}
		if v.Advapaym == "" {
			v.Advapaym = defVal
		}
		if v.Accopaya == "" {
			v.Accopaya = defVal
		}
		if v.Totalnoncliab == "" {
			v.Totalnoncliab = defVal
		}
		if v.Totliab == "" {
			v.Totliab = defVal
		}
		if v.Paresharrigh == "" {
			v.Paresharrigh = defVal
		}
		if v.Capisurp == "" {
			v.Capisurp = defVal
		}
		if v.Shorttermborr == "" {
			v.Shorttermborr = defVal
		}
	}
}

// checkKeyIndicatorDecimalNull 简单处理decimal 类型为空的情况
// TODO 后续更改为 https://github.com/shopspring/decimal
func checkKeyIndicatorDecimalNull(rows []*domain.KEY_INDICATOR) {
	defVal := "0.000000"
	for _, v := range rows {
		if v.Epsbasic == "" {
			v.Epsbasic = defVal
		}
		if v.Crps == "" {
			v.Crps = defVal
		}
		if v.Naps == "" {
			v.Naps = defVal
		}
		if v.Upps == "" {
			v.Upps = defVal
		}
		if v.Opncfps == "" {
			v.Opncfps = defVal
		}
		if v.Snpmarginconms == "" {
			v.Snpmarginconms = defVal
		}
		if v.Opprort == "" {
			v.Opprort = defVal
		}
		if v.Profitratio == "" {
			v.Profitratio = defVal
		}
		if v.Roeweighted == "" {
			v.Roeweighted = defVal
		}
		if v.Roediluted == "" {
			v.Roediluted = defVal
		}
		if v.Currentrt == "" {
			v.Currentrt = defVal
		}
		if v.Quickrt == "" {
			v.Quickrt = defVal
		}
	}
}

// checkKeyIndicatorSqDecimalNull 简单处理decimal 类型为空的情况
// TODO 后续更改为 https://github.com/shopspring/decimal
func checkKeyIndicatorSqDecimalNull(rows []*domain.KEY_INDICATOR_SQ) {
	defVal := "0.000000"
	for _, v := range rows {
		if v.Epsbasic == "" {
			v.Epsbasic = defVal
		}
		if v.Crps == "" {
			v.Crps = defVal
		}
		if v.Naps == "" {
			v.Naps = defVal
		}
		if v.Upps == "" {
			v.Upps = defVal
		}
		if v.Opncfps == "" {
			v.Opncfps = defVal
		}
		if v.Snpmarginconms == "" {
			v.Snpmarginconms = defVal
		}
		if v.Opprort == "" {
			v.Opprort = defVal
		}
		if v.Profitratio == "" {
			v.Profitratio = defVal
		}
		if v.Roeweighted == "" {
			v.Roeweighted = defVal
		}
		if v.Roediluted == "" {
			v.Roediluted = defVal
		}
		if v.Currentrt == "" {
			v.Currentrt = defVal
		}
		if v.Quickrt == "" {
			v.Quickrt = defVal
		}
	}
}
